package csu.web.mypetstore.web.servlet;

//import com.mysql.cj.Session;
import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Log;
import csu.web.mypetstore.service.LogService;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebFilter(filterName = "logFilter",urlPatterns = "/*")
public class LogFilter extends HttpFilter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //初始化
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("loginAccount");

        //放行
        chain.doFilter(request,response);

        if(account!=null){
            //获得string详细日期
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String action = (String) session.getAttribute("action");

            if(action == null)action = "signOut";
            //获得url
            String url = req.getRequestURL().toString();
            //插入log日志
            Log log = new Log(account.getUsername(),sdf.format(date),action,url);
            LogService logService = new LogService();
            logService.insertLog(log);
        }


    }
}
